package com.wenzi;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;

public class test {
    public static void main(String[] args)
    {
        createMark("D:\\图片素材\\210929\\moban\\10_121_188_621_653_.jpg","D:\\图片素材\\210929\\ui\\2.png");
    }

    /**
     * 在图片上添加水印图片和文字
     * @param filePath 原图片文件路径
     * @param watermark 水印图片文件路径
     * @return 添加成功返回true，否则返回false
     */
    public static boolean createMark(String filePath, String watermark)
    {
        //读取原图片
        ImageIcon imgIcon = new ImageIcon(filePath);
        Image theImg = imgIcon.getImage();
        //读取标签图片
        ImageIcon waterIcon = new ImageIcon(watermark);
        Image waterImg = waterIcon.getImage();

        int width = theImg.getWidth(null);
        int height = theImg.getHeight(null);

        //创建一个和原图片同大小的新空白图片
        BufferedImage bimage = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);
        Graphics2D g = bimage.createGraphics();
        //设置字体
        Font font = new Font("SansSerif",Font.BOLD,30);
        g.setFont(font);
        //设置前景色
        g.setColor(Color.red);
        //设置背景色
        g.setBackground(Color.white);
        //画原图
        g.drawImage(theImg, 0, 0, null);
        //画水印图
        g.drawImage(waterImg, 100, 100, null);
        //画字
        g.drawString("中国人民共和国", 100, 100);
        g.dispose();
        FileOutputStream out = null;
        try {
            out = new FileOutputStream("D:\\图片素材\\210929\\testResult\\12.png");
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
            JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bimage);
            param.setQuality(50f, true);
            encoder.encode(bimage, param);
        }
        catch (Exception e)
        {
            return false;
        }
        finally
        {
            if(out!=null)
            {
                try
                {
                    out.close();
                    out = null;
                }
                catch(Exception e)
                {}
            }
        }
        return true;
    }
}
